package com.qk.exception;

import com.qk.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public Result handlerException(Exception e) {
        log.error("异常是：{}", e.getMessage());
        return Result.error("发生异常，请联系管理员");
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Result handlerDuplicateKeyException(DuplicateKeyException e) {
        String errMsg = e.getMessage();
        if (errMsg.contains("Duplicate entry")) {
            String key = errMsg.substring(errMsg.indexOf("Duplicate entry"));
            String[] keys = key.split("-");
            return Result.error("已存在" + keys[keys.length - 1] + "为" + keys[0] + "的数据");
        }
        return Result.error("发生异常，请联系管理员");
    }

    @ExceptionHandler(BusinessException.class)
    public Result handlerBusinessesException(BusinessException e) {
        log.error("异常是：{}", e.getMessage());
        return Result.error(e.getMessage());
    }
}